
class Admin::DesignerPromotionsController < Admin::BaseController
  before_action :find_promotion, only: [:edit, :update, :destroy]

  def index
    @designer_promotions = DesignerPromotion.with_deleted.paginate(page: params[:page] || 1, per_page: params[:per_page] || 15).order("id desc")
  end

  def new
    @designer_promotion = DesignerPromotion.new
  end

  def create
    designer_promotion_params = params.require(:designer_promotion).permit!
    designer_promotion_params[:main_img] = get_first_img(designer_promotion_params)
    @designer_promotion = DesignerPromotion.new(designer_promotion_params)
    if @designer_promotion.save
      flash[:notice] = "新建百科成功"
      redirect_to admin_designer_promotions_path
    else
      flash[:notice] = "新建百科失败"
      render action: :new
    end
  end

  def edit
    render action: :new
  end

  def update
    designer_promotion_params = params.require(:designer_promotion).permit!
    designer_promotion_params[:main_img] = get_first_img(designer_promotion_params)
    @designer_promotion.attributes = designer_promotion_params

    if @designer_promotion.save
      flash[:notice] = "修改百科成功"
      redirect_to admin_designer_promotions_path
    else
      flash[:notice] = "修改百科失败"
      render action: :edit
    end
  end

  def destroy
    begin
      @designer_promotion.destroy
      flash[:notice] = "删除设计师活动成功"
      redirect_to admin_designer_promotions_path
    rescue
      flash[:notice] = "删除设计师活动失败"
      redirect_to :back
    end
  end

  private

  def find_promotion
    @designer_promotion = DesignerPromotion.with_deleted.find params[:id]
  end

end
